//
//  GoodsSepcSelectorCtr.swift
//  Aiwei
//
//  Created by zhu xietong on 2017/11/7.
//  Copyright © 2017年 zhu xietong. All rights reserved.
//

import Foundation
import soapp
import Eelay
import AsyncDisplayKit

private var subNode = "options"

public struct FormTypes{
    public static func types(names:[String]) ->[[String:Any]]
    {
        let tps = names.map({ (str) -> [String:Any] in
            return ["name":"\(str)","id":"\(str)"]
        })
        return tps
    }
}

extension Goods{
    
//    enum Spec {
//        static func new(whith goods:NSMutableDictionary,spec:NSMutableDictionary?) ->Goods.Spec
//        {
//
//
//            if  goods["goodsoption.hasoption",false.tag] == true.tag
//            {
//                if let _spec = spec
//                {
//                    return Goods.Spec.spec(spec: _spec, goods: goods)
//                }
//            }
//            else{
//
//            }
//        }
//
//        case none(goods:NSMutableDictionary)
//        case spec(spec:NSMutableDictionary,goods:NSMutableDictionary)
//        var price_str:String
//        {
//            get{
//                switch self {
//                case .none(goods: let goods):
//
//                default:
//
//                }
//            }
//        }
//
//    }
    
}


public enum SpecTask{
    case group(info:[String:Any])
    case groupSingleBuy
    case order
    case `default`
    
    
    var priceTag:NSMutableAttributedString{
        get{
            switch self {
            case .default,.groupSingleBuy,.order:
                return "¥ ".ui.font11.color(hex: "#FE5A5A").astring
            case .group(info:_):
                return "团购价  ".ui.bfont12.color(hex: "#1C9037").astring + "¥ ".ui.font12.color(hex: "#FE5A5A").astring
            }
        }
    }
    
    public var specPriceNode:String{
        get{
            switch self {
            case .default,.order:
                return "marketprice"
            case .groupSingleBuy:
                return "single_price"
            case .group(info:_):
                return "price"
            }
        }
    }
    
    public var hasnoSpecPriceNode:String{
        get{
            switch self {
            case .default,.order:
                return "marketprice"
            case .groupSingleBuy:
                return "singleprice"
            case .group(info: _):
                return "__groupsprice"
            }
        }
    }
    
}



open class GoodsSepcSelectorCtr: GesSideController,TableVConfig {
    
    public var specTask = SpecTask.default
    {
        didSet{
            specHeader.specTask = specTask
            footer.specTask = specTask
        }
    }
    
    public var nextActions:[SpecSelectorNext] = [.购买]{
        didSet{
            bar.nextBar.nextActions = nextActions
        }
    }
    
    public var nextAction:([String:Any],SpecSelectorNext)->Void = {_,_ in}
    
    open func touch(cell: Any, actionID: String, model: NSMutableDictionary) {}
    
    public var options:NSMutableArray = NSMutableArray()
    
    public var goods_spec_name = ""
    
    public var price_key:String{
        get{
            
            let vs = self.specifications.mutable_dictionary
            if vs.count > 0
            {
                var values = [String]()
                let count = self.options.count - 1
                for i in 0...count {
                    let value = vs["\(i)","#####"]
                    values.append(value)
                }
                var names = [String]()
                options.list({ (dict:NSMutableDictionary, i) in
                    if i < values.count
                    {
                        let k = dict["title","规格".loc]
                        var nameV = "XX"
                        let subs = DataNode.path(node: "item", dict, value: NSMutableArray())
                        subs.list({ (item:NSMutableDictionary, n) in
                            if item["id",""] == values[i]{
                                nameV = item["title",nameV]
                            }
                        })
                        names.append("\(k):\(nameV)")
                    }
                })
                self.goods_spec_name = names.joined(separator: "  ")
                values.sort { (str1, str2) -> Bool in
                    return str1.cg_floatValue < str2.cg_floatValue
                }
                return values.joined(separator: "_")
            }
            goods_spec_name = ""
            return ""
        }
    }
    
    
    
    public var priceObj:NSMutableDictionary?{
        get{
            if let v = DataNode<NSMutableDictionary>.path(node: "priceMap.\(price_key)", mo.model)
            {
                v["spec_key_name"] = self.goods_spec_name
                return v
            }
            return nil
        }
    }
    
    
    
    override open func mo_model_reload() {
        
        let spec_goods_price = DataNode.path(node: "spec_goods_price", mo.model, value: NSMutableDictionary())
        let priceMap = NSMutableDictionary()
        if let keys = spec_goods_price.allKeys as? [String]
        {
            for one in keys
            {
                var spec_ids = one.components(separatedBy: "_")
                spec_ids.sort { (str1, str2) -> Bool in
                    return str1.cg_floatValue < str2.cg_floatValue
                }
                let newKey = spec_ids.joined(separator: "_")
                if let priceObj = spec_goods_price.object(forKey: one) as? NSMutableDictionary
                {
                    priceObj["key"] = newKey
                    priceMap[newKey] = priceObj
                }
            }
        }
        self.mo.model["priceMap"] = priceMap
        let list = DataNode.path(node: "filter_spec", mo.model, value: NSMutableArray())
        self.options = list
    }
    
    let tableView = UITableView(frame: [0], style: .plain)
    var sections:TP.section{
        get{
            var sec: TP.section = TP.section()
            let list = options
            var section0 = [[String:Any]]()
            list.list { (dict:NSMutableDictionary, i) in
                
                let lever1Name = dict["title","规格".loc]
                let typeID = (dict["item.0.thumb",""].len > 0) ? "iconTag" :"textTag"
                let field = [
                    "id":typeID,
                    "title":lever1Name,
                    FK.fields:[
                        [
                            FK.selectMode:TagSelectMode.singleNoToggle.value,
                            FK.options:dict["item"],
                            FK.field:StrField(id: "\(i)", defaultV: nil, need: true, hiden: false, rule:
                                JoRule(reg: "^[\\s\\S]{1,1100}$", nil_msg: "请选择\(lever1Name)", err_msg: "请选择\(lever1Name)")),
                        ],
                    ]
                ] as [String : Any]
                section0.append(field)
            }
            sec.append(section0)
            
//            let sec:TP.section = [
//                [
//                    [
//                        "id":"textTag",
//                        "title":"尺寸",
//                        FK.fields:[
//                            [
//                                FK.selectMode:TagSelectMode.singleToggle.value,
//                                FK.options:FormTypes.types(names: ["20","30","40","20"]),
//                                FK.field:StrField(id: "chicun", defaultV: nil, need: false, hiden: false, rule:
//                                    JoRule(reg: "^[\\s\\S]{1,200}$", nil_msg: "", err_msg: "")),
//                            ],
//                        ]
//                    ],
//                    [
//                        "id":"iconTag",
//                        "title":"颜色",
//                        FK.fields:[
//                            [
//                                FK.selectMode:TagSelectMode.singleToggle.value,
//                                FK.options:FormTypes.types(names: ["红色","蓝色","紫色","白色","绿色","黄色","金色"]),
//                                FK.field:StrField(id: "chicun", defaultV: nil, need: false, hiden: false, rule:
//                                    JoRule(reg: "^[\\s\\S]{1,200}$", nil_msg: "", err_msg: "")),
//                                ],
//                        ]
//                    ]
//                ],
//                [
//                ],
//            ]
            return sec
        }
    }
    
    let selector:TP.selector = [
        "id<textTag>":规格选择Cell<GgStrechTextKit>.self,
        "id<iconTag>":规格选择Cell<GgIconKit>.self,
    ]
    
    var specifications = [String:Any]()
    
    public let bar = ConfirmBar()
    let specHeader = CurrentBar()
    
    
    weak var fromController:TypeInitController? = nil{
        didSet{
            bar.mo.controller = fromController
        }
    }


    
    
    override open func viewDidLoad() {
        self.side = .bottom(height: Sheight * 0.7)
        
        super.viewDidLoad()
        gestureAble = true
        let line = UIView()
        
        specHeader.backgroundColor = ._background
        bar.backgroundColor = ._background
        footer.backgroundColor = ._background
        
        let headerH = 80 + AppTheme.edge * 2.0
        jo_contentView.eelay = [
            [specHeader,[ee.T.L.R,[0,0,0]],"\(headerH)"],
            [tableView,[ee.L.R],[specHeader,ee.B,ee.T],[bar,ee.T,ee.B]],
            [bar,[ee.L.B.R,[0.+1000,1.+1000,0.+1000]]],
        ]
        
        jo_contentView.backgroundColor = .clear
        
        let delete_bt = UIButton()
        let img = UIImage(named:"delete_tag")
        delete_bt.setImage(img, for: .normal)
        jo_contentView.eelay = [
            [delete_bt,[specHeader,ee.T.R,[8,-4]],"36",36],
        ]
        delete_bt.addTarget(self, action: #selector(close), for: .touchUpInside)
        
        
        line.backgroundColor = UIColor.clear
        self.configTables(tables: tableView)
        tableView.buildDynamicHeight(height: 100)
        tableView.separatorStyle = .none
        tableView.load(sections: sections, selector: selector)
        tableView.backgroundColor = ._background
        tableView.reloadData()
        self.gestureAble = false
        bar.controller = self
        weak var wself = self
        bar.nextAction = { values,type in
            guard let ws = wself else {
                return
            }
            ws.nextAction(values,type)
        }
        
        specHeader.mo.detail = self.mo.detail
        footer.mo.detail = self.mo.detail
        bar.mo.detail = self.mo.detail
        
        
        bar.pramasGetter  = {
            var values = [String:Any]()
            var ok = false
            guard let ws = wself else {
                return (false,[String:Any]())
            }
            let specs = JoPaw.paw(tableView: ws.tableView)
            if specs.validate
            {
                values = values + specs.values
                ok = true
                let num = JoPaw.paw(list: [[FK.field:ws.footer.mo.model]].mutable_array)

                if num.validate{
                    values = values + num.values
                }
                else{
                    ok = false
                }
            }
            return (ok,values)
        }

        __notice.observer(FK.Notice.valueChange) { (notyType, notify) in
            guard let obj = notify.object as? GoodsSepcSelectorCtr,let ws = wself else{return}
            if obj !== ws{
                return
            }
            if let info = notify.userInfo as? [String:Any]
            {
                let values = info.mutable_dictionary
                
                wself?.specifications[values["__id",""]] = values["__value",""]
                ws.checkGoodsInfo()
                
                
                let vl = values["__value",""]
                let options = DataNode.path(node: "options", values, value: NSMutableArray())
                options.list({ (obj:NSMutableDictionary, i) in
                    if obj["id",""] == vl{
                        ws.specHeader.recentSpec = obj
                    }
                })
                
            }
        }
    }
    
    func checkGoodsInfo() {
//        print("------|\(specifications.count)===|\(self.options.count)")
//        if let price_obj = self.priceObj{
//            print("===kkjjj|\(price_obj)")
//        }

        if specifications.count >= self.options.count
        {
            if let price_obj = self.priceObj{
                bar.mo.model = price_obj
                specHeader.mo.model = price_obj
                footer.mo.detail = price_obj
                return
            }
        }
        specHeader.mo.model = NSMutableDictionary()
        bar.mo.model = NSMutableDictionary()
    }
    
    
    override open var backgroundView: UIView{
//        let blurView = UIVisualEffectView()
//        let sty = UIBlurEffectStyle.extraLight
//        let blurEffect = UIBlurEffect(style: sty)
//        blurView.effect = blurEffect
//        return blurView
        let view = UIView()
        view.backgroundColor = .clear
        let v = UIView()
        v.backgroundColor = ._tableBackground
        view.eelay = [
            [v,[ee.T,24],[ee.L.R.B]]
        ]
        return view
    }
    
    
    let footer = NumFooter()
    
    
    public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0
        {
            return footer
        }
        return nil
    }
    
    public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0
        {
            return 50
        }
        return 0
    }
    
  
    
    override open func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}




